package mysql

import (
	"gorm.io/gorm"
	"shopping/logger"
	"shopping/model"
)

// ProductDao 商品Dao
type ProductDao struct {
	db *gorm.DB
}

// NewProductDao 实例化
func NewProductDao(db *gorm.DB) *ProductDao {
	return &ProductDao{
		db: db,
	}
}

// Migration 生成表
func (dao *ProductDao) Migration() {
	err := dao.db.AutoMigrate(&model.Product{})
	if err != nil {
		logger.Log.Error(err.Error())
	}
}

// Update 更新
func (dao *ProductDao) Update(updateProduct model.Product) error {
	saveProduct, err := dao.FindBySku(updateProduct.SKU)
	if err != nil {
		return err
	}
	err = dao.db.Model(&saveProduct).Updates(updateProduct).Error
	return err
}

// FindBySku 根据sku查询商品数据
func (dao *ProductDao) FindBySku(sku string) (*model.Product, error) {
	var product *model.Product
	err := dao.db.Where(model.Product{BaseModel: model.BaseModel{DelFlag: 0}, SKU: sku}).First(&product).Error
	if err != nil {
		return nil, err
	}
	return product, nil
}

// SearchByString 搜索返回分页结果
func (dao *ProductDao) SearchByString(str string, pageIndex, pageSize int) ([]model.Product, int) {
	var products []model.Product
	covertedStr := "%" + str + "%"
	var count int64
	dao.db.Where("DelFlag = ?", 0).Where("name like ? or sku like ?", covertedStr,
		covertedStr).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&products).Count(&count)
	return products, int(count)
}

// Create 创建商品
func (dao *ProductDao) Create(p *model.Product) error {
	result := dao.db.Create(p)
	return result.Error
}

// GetAll 查询所有商品
func (dao *ProductDao) GetAll(pageIndex, pageSize int) ([]model.Product, int, error) {
	var products []model.Product
	var count int64
	err := dao.db.Where("DelFlag = ?", 0).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&products).Count(&count).Error
	return products, int(count), err
}

// DeleteBySku 根据sku删除商品数据
func (dao *ProductDao) DeleteBySku(sku string) error {
	currentProduct, err := dao.FindBySku(sku)
	if err != nil {
		return nil
	}

	currentProduct.DelFlag = 1
	err = dao.db.Save(currentProduct).Error
	return err
}
